<template>
  <div class="animate__animated animate__fadeIn">
    <el-card>
      <!--搜索部分-->
      <div class="search-container"  >
        <div class="search-box" v-show="searchShow">
          <el-input prefix-icon="el-icon-search" v-model="searchCondition.username" placeholder="请输用户名称..."
                    size="small" clearable @clear="initconsumer" style="margin-right: 10px;width: 25%;"/>
          <el-input prefix-icon="el-icon-search" v-model="searchCondition.phonenum" placeholder="请输入手机号码..."
                    size="small" clearable @clear="initconsumer" style="margin-right: 10px;width: 25%;"/>
          <el-select size="small" v-model="searchCondition.isDisable" placeholder="用户状态"
                     clearable @clear="initconsumer" style="margin-left: 10px;width: 15%;">
            <el-option
                v-for="item in isDisable"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
           <el-button icon="el-icon-search" type="primary" size="small" @click="initconsumer"  style="margin-left: 10px">搜索</el-button>
    
          <el-button :disabled="deleteList.length === 0" slot="reference" icon="el-icon-delete" type="danger" size="small" @click="deleteLogsInfo">批量删除</el-button>
       
        </div>
          <!--添加部分-->
        <div class="save-container">
          <!--添加-->
          <div class="save-box">
            <el-button type="success" size="small" plain icon="el-icon-plus" @click="toSave()">添加用户
            </el-button>
          </div>
          <!--关闭-->
          <div class="close-box">
            <el-tooltip content="关闭查询" placement="bottom">
              <el-button type="primary" size="small" plain circle icon="el-icon-search"
                         @click="searchShow = !searchShow"/>
            </el-tooltip>
            <el-tooltip content="刷新数据" placement="bottom">
              <el-button type="success" size="small" plain circle icon="el-icon-refresh" @click="initconsumer"/>
            </el-tooltip>
            <el-tooltip content="显隐列" placement="bottom">
              <el-button type="warning" size="small" plain circle icon="el-icon-menu" @click="transferVisible = true"/>
            </el-tooltip>
          </div>
        </div>
      </div>

      <!--表格部分-->
      <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="consumerList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="selectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('用户名称')"
            align="center"
            prop="username"
            label="用户名称"
            min-width="100">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('用户昵称')"
            align="center"
            prop="nickname"
            label="用户昵称"
            min-width="100">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('邮箱')"
            align="center"
            prop="email"
            label="邮箱"
            min-width="150">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('电话')"
            align="center"
            prop="phonenum"
            label="电话"
            width="150">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('性别')"
            align="center"
            label="性别"
            width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.gender== -1" >男</el-tag>
            <el-tag v-else >女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('状态')"
            align="center"
            label="状态"
            width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDisable" type="danger">禁用</el-tag>
            <el-tag v-else >正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('创建者')"
            align="center"
            prop="createBy"
            label="创建者"
            width="100">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('创建时间')"
            align="center"
            prop="gmtCreate"
            label="创建时间"
            width="200">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ scope.row.gmtCreate }}
          </template>
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('修改者')"
            align="center"
            prop="updateBy"
            label="修改者"
            width="100">
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('修改时间')"
            align="center"
            prop="gmtUpdate"
            label="修改时间"
            min-width="200">
                <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ scope.row.gmtUpdate }}
          </template>
        </el-table-column>
        <el-table-column
           v-if="!transferValue.includes('备注')"
            align="center"
            prop="remark"
            label="备注"
            width="100">
        </el-table-column>
        <el-table-column
            align="center"
            width="260"
            label="操作">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="toUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-key"  @click="resetPassword(scope.row)">重置密码</el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteLogInfo(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页部分-->
      <el-pagination
          class="page"
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="searchCondition.current"
          :page-sizes="[8, 16, 32]"
          :page-size="8"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!--显隐列 弹出层-->
    <el-dialog
        title="显隐列设置"
        :visible.sync="transferVisible"
        width="45%"
        append-to-body
        center>
      <el-transfer
          v-model="transferValue"
          :data="transferData"
          :titles="transferTitles">
      </el-transfer>
    </el-dialog>

 <!--新增 弹出层-->
    <el-drawer
       :title="consumerVo.userId === -1?'新增用户信息':'修改用户信息'"
        :visible.sync="saveMenuVisible"
        append-to-body
        direction="rtl"
        size="28%"
        :before-close="leave">
      <div class="save-container">
        <el-form ref="consumerVoCheck" :rules="rule" :model="consumerVo" label-width="90px" class="demo-ruleForm">
        
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="consumerVo.username" border label="menu" placeholder="请输入用户名称..."/>
          </el-form-item>
          <el-form-item 
          v-if="consumerVo.userId === -1" label="密码" prop="password">
            <el-input :type="passw" v-model="consumerVo.password" border label="menu" placeholder="请输入密码...">
           <%-- input中加图标必须要有slot="suffix"属性，不然无法显示图标 --%>
           <i slot="suffix" :class="icon" @click="showPass"></i> 
          </el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="consumerVo.nickname" border label="menu" placeholder="请输入用户昵称..."/>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
          <el-select size="small" v-model="consumerVo.roleId" 
                       style="width: 45%;">
            <el-option
                v-for="item in role"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId">
            </el-option>
          </el-select>
          </el-form-item>
                   <el-form-item label="用户状态"  prop="isDisable">
          <el-select size="small" v-model="consumerVo.isDisable" 
                       style="width: 45%;">
            <el-option
                v-for="item in isDisable"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="consumerVo.email" border label="menu" placeholder="请输入邮箱..."/>
          </el-form-item>
          
          <el-form-item label="手机号码" prop="phonenum">
            <el-input v-model="consumerVo.phonenum" border label="menu" placeholder="请输入手机号码..."/>
          </el-form-item>
          <el-form-item label="用户性别">
          <el-select size="small" v-model="consumerVo.gender" 
                       style="width: 45%;">
            <el-option
                v-for="item in gender"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
          
          <el-form-item label="备注信息" align="center">
            <el-input type="textarea" :rows="3" placeholder="请输入备注信息..." v-model="consumerVo.remark"/>
          </el-form-item>
          <el-form-item align="center">
            <el-button icon="el-icon-sunny" size="small" type="success" plain @click="saveMenuContent('consumerVoCheck')">
              确定
            </el-button>
            <el-popconfirm
                v-if="consumerVo.userId === -1"
                style="margin-left: 10px"
                title="确定要重置用户信息吗？"
                @confirm="clearForm">
              <el-button icon="el-icon-refresh" size="small" type="warning" plain slot="reference">重置</el-button>
            </el-popconfirm>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>


  </div>
</template>

<script>
import {formatTimeToYMD} from "../../../utils/timeUtil";
import {listConsumer} from "../../../api/user/user";
import {transferTitles, transferData} from "@/assets/const/user";
import {saveConsumer,
        deleteConsumer,
        deleteConsumerList,
        listAllRole,
        resetPassword,
        updateConsumer
} from "../../../api/user/user";
import {resultCheck} from "../../../utils/result";



export default {
  data() {
    return {
      consumerList: [],
      loading: false,
      deleteList: [],
      total: 0,
      time: [],
      switchValue: true, // 设置默认值为开启状态
      searchShow: true,   //查询功能是否开启
      searchCondition: {
        current: 1,
        size: 8,
        username: "",
        phonenum: "",
        isDisable: null
      },
      isDisable: [
        {value: 0, label: "正常"},
        {value: 1, label: "禁用"}
      ],
      gender: [
        {value: -1, label: "男"},
        {value: 1, label: "女"}
      ],
      role: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //默认密码
      defaultPassword:'123456',
      //用于改变Input类型
      passw:"password",
      //用于更换Input中的图标
      icon:"el-input__icon el-icon-view",
      //=======================  穿梭表单  ===========================
      transferTitles: transferTitles(),  //穿梭表单title
      transferValue: ['创建者', '创建时间', '修改者', '修改时间'],               //穿梭表单选中数据
      transferData: transferData(),      //穿梭表单数据
      transferVisible: false,            //显隐列是否开启
      //=======================  用户  ===========================
      saveMenuVisible: false,   //新增用户
      menuType: "menu",
      rule: {
        username: [{required: true, message: '用户名称不能为空！', trigger: 'blur'}],
        nickname: [{required: true, message: '用户昵称不能为空！', trigger: 'blur'}],
        roleId: [{required: true, message: '用户角色不能为空！', trigger: 'blur'}],
        isDisable: [{required: true, message: '用户状态不能为空！', trigger: 'blur'}],
        password: [{required: true, message: '密码不能为空！', trigger: 'blur'}]
      },
      consumerVo: {
        userId: -1,
        username: '',
        password: '123456',
        nickname: '',
        email: '',
        phonenum: '',
        gender: '',
        isDisable: 0,
        remark: '',
        roleId: 2
      },
        init: {
        userId: -1,
        username: '',
        password: '123456',
        nickname: '',
        email: '',
        phonenum: '',
        gender: '',
        isDisable: 0,
        remark: '',
        roleId: 2
      }
    }
  },
  mounted() {

        this.initconsumer();
        
  },
  methods: {
    //=======================  查询操作  ===========================
    initconsumer() {
      this.loading = true;
      listConsumer(this.searchCondition).then(res => {
        var data = resultCheck(res, false);
        this.consumerList = data.data;
        this.total = data.total;
        this.loading = false;
      });
    },
    initrole() {
      listAllRole().then(res => {
        this.role = res.data;
      });
    },
    sizeChange(val) {
      this.searchCondition.size = val;
      this.initconsumer();
    },
    currentChange(val) {
      this.searchCondition.current = val;
      this.initconsumer();
    },
    // 时间变换
    change() {
      this.searchCondition.beginTime = formatTimeToYMD(this.time[0]);
      this.searchCondition.endTime = formatTimeToYMD(this.time[1]);
    },
     // 批量删除
    selectionChange(val) {
        this.deleteList = val;
    },
    //密码的隐藏和显示
    showPass(){
　　　　　　　　　　//点击图标是密码隐藏或显示
               if( this.passw=="text"){
                   this.passw="password";
                   //更换图标
                   this.icon="el-input__icon el-icon-view";
               }else {
                   this.passw="text";
                   this.icon="el-input__icon el-icon-loading";
               };
    },

    //  重置密码
    resetPassword(data) {
        this.$confirm(`确认要重置用户密码为123456吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
         }).then(_ => {
        data.password = this.defaultPassword;
        resetPassword(data).then(res => {
         resultCheck(res, true);
         this.initconsumer();
       });
      });
    },
   //=======================  删除操作  ===========================
    //  删除用户信息
    deleteLogInfo(id) {
        this.$confirm(`确认要删除此用户信息吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
         }).then(_ => {
        deleteConsumer(id).then(res => {
         resultCheck(res, true);
         this.initconsumer();
       });
      });
    },
    //  批量删除用户信息
    deleteLogsInfo() {

    this.$confirm(`确认要删除选中的用户信息吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
         }).then(_ => {
        const idList = [];
        this.deleteList.forEach(item => {
         idList.push(item.userId);
    
         })
       deleteConsumerList(idList).then(res => {
         resultCheck(res, true);
         this.initconsumer();
       });
       });
    },
    //=======================  新增/修改用户部分  ===========================
    leave() {
      this.$confirm('数据不会临时保存，切勿离开此界面！')
          .then(_ => {
            this.consumerVo = this.init;
            this.saveMenuVisible = false;
          });
    },
    //  清空表单信息
    clearForm() {
       this.consumerVo = this.init;
    },
    //  跳转至修改界面
    toUpdate(data) {
      this.initrole();
      this.consumerVo = data;
      this.saveMenuVisible = true;
       
    },
    //  跳转至新增界面
    toSave() {
      this.initrole();
      this.consumerVo.userId = -1;
      this.menuType = 'content';
      this.saveMenuVisible = true;   
    },
    //  添加用户信息
    saveMenuContent(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.consumerVo.userId == -1) {
              saveConsumer(this.consumerVo).then(res => {
                resultCheck(res, true);
                this.consumerVo = this.init;
                this.initconsumer();
              });  
          } else {
            updateConsumer(this.consumerVo).then(res => {
              resultCheck(res, true);
              this.consumerVo = this.init;
              this.initconsumer();
            });   
          }
          this.saveMenuVisible = false;
        }
      });
    },
  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  flex-direction: column;
}

.search-box {
  display: flex;
  justify-content: left;
}

.time-box {
  display: flex;
  justify-content: left;
  margin-top: 10px;
}
.save-container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.page{
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
</style>